package com.colbby.datahouse.message;

import java.util.ArrayList;
import java.util.List;

import org.jinghouyu.json.core.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.colbby.datahouse.message.handler.ContentHandler;
import com.colbby.datahouse.message.handler.TradeHandler;
import com.taobao.api.internal.tmc.Message;
import com.taobao.api.internal.tmc.MessageHandler;
import com.taobao.api.internal.tmc.MessageStatus;
import com.taobao.api.internal.tmc.TmcClient;
import com.taobao.top.link.LinkException;

public class MessageListener implements MessageHandler{

	private final List<ContentHandler> handlers = new ArrayList<>();
	
	private static final Logger logger = LoggerFactory.getLogger(MessageListener.class);
	
	{
		handlers.add(new TradeHandler());
	}
	
	@Override
	public void onMessage(Message message, MessageStatus status) throws Exception {
		try {
			String content = message.getContent();
			System.out.println(content);
			JsonObject json = JsonObject.fromObject(content);
			handle(json);
		} catch(Exception e) {
			logger.error("", e);
			e.printStackTrace();
			status.fail();
		} finally {
			ConnectionUtils.release();
		}
	}
	
	private void handle(JsonObject json) {
		ContentHandler handler = null;
		for(ContentHandler h : handlers) {
			if(h.check(json)) {
				handler = h;
				break;
			}
		}
		if(handler != null) {
			handler.handle(json);
		} else {
			logger.warn("no handler for data : " + json.toJsonString());
		}
	}
	
	public static void main(String[] args) {
		TmcClient client = new TmcClient("21699741", "91e5ae80d7a97968c84f0205111c05b9");
		client.setMessageHandler(new MessageListener());
		try {
			client.connect();
		} catch (LinkException e) {
			e.printStackTrace();
		}
		synchronized (client) {
			try {
				client.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
